package com.sanhuo.security.filter;

import com.sanhuo.lib.ExceptionUtil;
import com.sanhuo.lib.exception.GlobalException;
import com.sanhuo.security.RoleVO;
import com.sanhuo.security.UserVo;
import com.sanhuo.security.entity.User;
import com.sanhuo.security.global.ResponseEnum;
import com.sanhuo.security.service.RoleService;
import com.sanhuo.security.service.UserTokenService;
import com.sanhuo.security.uitls.UserHolder;
import com.sanhuo.utils.basic.BeanUtil;
import com.sanhuo.utils.basic.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.logging.Logger;

@Component
public class TokenFilter extends HandlerInterceptorAdapter {
    private final String TOKENSTR = "token";
    private static Logger log = Logger.getLogger(TokenFilter.class.getName());
    private final String USER = "author";
    @Autowired
    private UserTokenService userTokenService;
    @Autowired
    private RoleService roleService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取请求的请求体中属性为"token"的值
        String token = obtainToken(request);
        //如果token为空,说明该用户没有登录,抛出对应的错误代码和错误信息
        ExceptionUtil.throwException(StringUtil.isBlank(token), ResponseEnum.LOGIN_FAILE.getCode(),
                ResponseEnum.LOGIN_FAILE.getMsg());
        //通过token从内存中获取对应的user信息
        UserVo userVo = UserHolder.user();
        if (BeanUtil.isNotNull(userVo)) {
            return tokenVerify(token.equals(userVo.getToken()));
        } else {
            User user = userTokenService.findUserByToken(token);
            userVo = new UserVo();
            BeanUtil.copyBean(user, userVo);
            if (StringUtil.isNotBlank(user.getRoleId())) {
                RoleVO role = roleService.detail(user.getRoleId());
                if (BeanUtil.isNotNull(role)) {
                    userVo.setRole(role);
                }
            }
            userVo.setToken(token);
            UserHolder.put(token, userVo);
            return tokenVerify(user != null);
        }
    }


    public String obtainToken(HttpServletRequest request) {
        return request.getParameter(TOKENSTR);
    }


    private boolean tokenVerify(Boolean condition) {
        if (condition) {
            return true;
        } else {
            throw new GlobalException(ResponseEnum.LOGIN_FAILE.getCode(),
                    ResponseEnum.LOGIN_FAILE.getMsg());
        }
    }
}
